// Functions..
function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	
	if(isNaN(num)){
		num = "0";
	}
		
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	
	if(cents < 10){
		cents = "0" + cents;
	}
		
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++){
		num = num.substring(0,num.length-(4*i+3))+','+
		num.substring(num.length-(4*i+3));
	}
	
	return (((sign)?'':'-') + num);
}

function validateCurrency(strPrice) {
   var reg = /^\d+(,\d{3})*$/;
   if (trim(strPrice)=="") {
	   	return true;
   }
   if(!reg.test(strPrice)) {
   	  	return false;		
   }
   return true;
}

var paramPasswordLength = 8;
function validatePasswordPolicy(password) {
	var currentValidCount = 0;
	var requiredValidCount = 3;
	
	var rules = {
			lower:    1,
			upper:    1,
			numeric:  1,
			special:  1,
			length:   [paramPasswordLength, Infinity]
		},
		regex = {
			lower:   /[a-z]/g,
			upper:   /[A-Z]/g,
			numeric: /[0-9]/g,
			special: /[\W_]/g
		};
	
	if (password.length < rules.length[0] || password.length > rules.length[1]) {
		return false;
	}

	if ((password.match(regex.special) != null) && (password.match(regex.special).length >= rules.special)) { 
		currentValidCount++;
	} else { 
		return false;
	}
	
	// lowercase
	if ((password.match(regex.lower) != null) && (password.match(regex.lower).length >= rules.lower)) {
		currentValidCount++;
	}

	// uppercase
	if ((password.match(regex.upper) != null) && (password.match(regex.upper).length >= rules.upper)) {
		currentValidCount++;
	}

	// numeric
	if ((password.match(regex.numeric) != null) && (password.match(regex.numeric).length >= rules.numeric)) {
		currentValidCount++;
	}

	if (currentValidCount >= requiredValidCount) {
		return true;
	} else {
		return false;
	}
}

function trim(str) {
   return str.replace(/(^\s*)|(\s*$)/g, "");
}

function isValidInteger(num) {
   num = trim(num);
   var origVal = parseFloat(num);
   var newVal = parseInt(num);
   var diff = origVal - parseFloat(newVal);
   if(isNaN(num) || num.indexOf('.') >= 0) {  	  
      return false;
   } else if(diff != 0) {
      return false;
   }
   else return true;
}

(function($) {
	  $.fn.emptySelect = function() {
	    return this.each(function(){
	      if (this.tagName=='SELECT') this.options.length = 0;
	    });
	  };

	  $.fn.loadSelect = function(optionsDataArray) {
	    return this.emptySelect().each(function(){
	      if (this.tagName=='SELECT') {
	        var selectElement = this;
	        $.each(optionsDataArray,function(index,optionData){
	          var option = new Option(optionData.name,
	                                  optionData.id);
	          if ($.browser.msie) {
	            selectElement.add(option);
	          }
	          else {
	            selectElement.add(option,null);
	          }
	        });
	      }
	    });
	  };
	})(jQuery);

$.fn.datebox.defaults.formatter = function(date){
	var y = date.getFullYear();
	var m = date.getMonth()+1;
	var d = date.getDate();
	return ((d<10?('0'+d):d)+'-'+(m<10?('0'+m):m))+'-'+y;
};
$.fn.datebox.defaults.parser = function(s){
	if (!s) return new Date();
	var ss = s.split('-');
	var m = parseInt(ss[1],10);
	var d = parseInt(ss[0],10);
	var y = parseInt(ss[2],10);
	if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
		return new Date(y,m-1,d);
	} else {
		return new Date();
	}
};

//Pagination..
var totalRows;
var pageSize;
var currentPage;

var isFirstLoad = true;

function pageSelectCallback(page_index, jq){
   	if (isFirstLoad) {
   		isFirstLoad = false;
   		return false;
   	}
   	
   	$("input[name='offset']").val(page_index * pageSize);
   	$("input[name='output']").val("");

    $("#form").trigger("submit");
}

function ajaxPost(uri, val) {
    jQuery.ajax(uri, {
        data: val,
        type: 'post',
        success: function (data) {
            if (data.success) {
                jQuery.messager.alert('Success', data.message, 'info');                
            } else {
                jQuery.messager.alert('Error', data.message, 'error');
            }
        },
        error: function () {
            jQuery.messager.alert('Error', 'Opss.. Please try again..', 'error');
        }
    });
}

$(document).ready(function() {
	
	totalRows = $("input[name='totalRows']").val();
	pageSize = $("input[name='pageSize']").val();
	currentPage = $("input[name='offset']").val() / pageSize;

	$(".pagination").pagination(totalRows, 
            {callback:pageSelectCallback, 
    		items_per_page:pageSize,
    		current_page:currentPage,
    		num_edge_entries:2});
	
	$(".wysiwyg").wysiwyg();
	
//	var styleTag = $('iframe').contents().find('head').append('<style></style>').children('style');
//	if (styleTag) {
//		styleTag.text('body{ font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; font-size: 12px; color: #333; }');
//	}
	
});

//Effect
$(document).ready(function(){
	$(".info").click(function() {
		$(this).slideUp("fast");							 	  
	});
	
	$("#contact-link").click(function(){
		$("#contact-form").dialog("open");
	});
	
	$(".searchLookup").click(function(){
		lookup(0, true);
	});
	
	$('#mask, .window .close').click(function (e) {
		e.preventDefault();
		
		$('#'+div).hide();
		
		$('#mask, .window').hide();
	});
});

var xPageSize = 10;
var xIsFirstLoad = true;
var mode = '';
var lookupMode = ''; // employee, costCenter, building, vendor
var inputBox = '';
var trigger =''; // multiple input box
var div = '';
var tbl = '';

var customInputBox = '';
var customInputBox1 = '';
var singleInputBox = '';
var fieldNameInputBox = '';
var divisi = '';

function pageSelectCallbackAjaxLookup(page_index, jq){
	if (xIsFirstLoad) {
   		xIsFirstLoad = false;
   		return false;
   	}

	lookup(page_index*xPageSize, false);
		
   	return false;
}

function popupWindow(obj, height) {
	var xx = $('#xx');

	//Get the screen height and width
	var maskHeight = $(document).height();
	var maskWidth = $(document).width();
	
	if(maskHeight < 800) {
		maskHeight = 800;
	}

	//Set height and width to mask to fill up the whole screen
	$('#mask').css({'width':maskWidth,'height':maskHeight});

	//transition effect
	$('#mask').fadeIn(500);
	$('#mask').fadeTo("slow",0.5);

	//Get the window height and width
	var winH = $(document).height();
	var winW = $(document).width();

	$(xx).css({'width':800,'height':height});
	
	var offset = $(obj).offset();
	var top = offset.top;
	if ((offset.top + height) > winH) {
		top = top - (height - (winH - offset.top));
	}
	
	//Set the popup window to center
	$(xx).css('top', top - 100);
	$(xx).css('left', winW/2-$(xx).width()/2);
	
	lookup(0, true);
	
	//transition effect  
	$(xx).fadeIn(1000);
}

function lookup(offset, isInitPagination) {
    var url = '';
    var options = '';
    div = '';
    tbl = '';
    
    if(lookupMode == 'employee') {
    	div = 'divEmployee';
	    tbl = 'tblEmployee';
	    url = contextPathUrl + '/ajax/lookup/employee';
	    
	    var id = $("#"+div+" input[name='id']").val();
		var name = $("#"+div+" input[name='name']").val();
		
		options = {offset:offset,id:id,name:name,division:divisi};
    }
    if(lookupMode == 'branch') {
    	div = 'divBranch';
	    tbl = 'tblBranch';
	    url = contextPathUrl + '/ajax/lookup/branch';
	  
	    if (mode == 'gemsBuilding') {
	    	url = url + '?mode=gemsBuilding';
	    }
	    
	    var kodeCabang = $("#"+div+" input[name='kodeCabang']").val();
		var namaCabang = $("#"+div+" input[name='namaCabang']").val();
		var regionalBisnis = $("#"+div+" :input[name='regionalBisnis']").val();
		var hseRegional = $("#"+div+" :input[name='hseRegional']").val();
		
		options = {offset:offset,kodeCabang:kodeCabang,namaCabang:namaCabang,regionalBisnis:regionalBisnis,hseRegional:hseRegional};
    }
    if(lookupMode == 'department') {
    	div = 'divDepartment';
	    tbl = 'tblDeparment';
	    url = contextPathUrl + '/ajax/lookup/department';
	    
	    var tableCode = $("#"+div+" input[name='tableCode']").val();
		var description = $("#"+div+" input[name='description']").val();
		
		options = {offset:offset,tableCode:tableCode,description:description,parentTableCode:divisi};
    }
    if(lookupMode == 'selectedParties') {
    	div = 'divSelectedParties';
	    tbl = 'tblSelectedParties';
	    url = contextPathUrl + '/ajax/lookup/employee';
	    
	    var id = $("#"+div+" input[name='id']").val();
		var name = $("#"+div+" input[name='name']").val();
		
		options = {offset:offset,id:id,name:name};
    }
    if(lookupMode == 'picIncident') {
    	div = 'divUser';
	    tbl = 'tblUser';
	    url = contextPathUrl + '/ajax/lookup/picIncident';
	    
	    var id = $("#"+div+" input[name='id']").val();
		var name = $("#"+div+" input[name='name']").val();
		
		options = {offset:offset,id:id,name:name};
    }

    $('#'+div).show();
    
	$('#'+tbl+' tbody tr').remove();
	$('#'+tbl+' tbody').append('<tr><td colspan="25" align="center"><img src="'+spinnerUrl+'"/> Loading..</td></tr>'); // loading sign
	
	// ajax call
	$.getJSON(url,options,
			function(data){
				$('#'+tbl+' tbody tr').remove();
				
					$.each(data.recs,function(index,item){
						var i = offset+index+1;
						if(lookupMode == 'employee') {
							$('#'+tbl+' tbody').append('<tr style="cursor: pointer;" onclick="getValAndClose(this);"><td>'+i+'<input type="hidden" name="phone" value="'+item.phone+'"/><input type="hidden" name="email" value="'+item.email+'"/><input type="hidden" name="address" value="'+item.address+'"/><input type="hidden" name="dept" value="'+item.dept+'"/></td><td>'+item.id+'</td><td>'+item.name+'</td></tr>');
						}
						if(lookupMode == 'branch') {
							$('#'+tbl+' tbody').append('<tr style="cursor: pointer;" onclick="getValAndClose(this);"><td>'+i+'<input type="hidden" name="regionalBisnisName" value="'+item.regionalBisnisName+'"/><input type="hidden" name="kota" value="'+item.kota+'"/><input type="hidden" name="jumlahPenghuni" value="'+item.jumlahPenghuni+'"/><input type="hidden" name="alamat" value="'+item.alamat+'"/></td><td>'+item.kodeCabang+'</td><td>'+item.namaCabang+'</td></tr>');
						}
						if(lookupMode == 'department') {
							$('#'+tbl+' tbody').append('<tr style="cursor: pointer;" onclick="getValAndClose(this);"><td>'+i+'<input type="hidden" name="tableType" value="'+item.tableType+'"/></td><td>'+item.tableCode+'</td><td>'+item.description+'</td></tr>');
						}
						if(lookupMode == 'selectedParties') {
							$('#'+tbl+' tbody').append('<tr style="cursor: pointer;"><td>'+i+'<input type="checkbox" value="'+item.email+'" /><input type="hidden" name="phone" value="'+item.phone+'"/><input type="hidden" name="email" value="'+item.email+'"/><input type="hidden" name="address" value="'+item.address+'"/></td><td>'+item.id+'</td><td>'+item.name+'</td></tr>');
						}
						if(lookupMode == 'picIncident') {
							$('#'+tbl+' tbody').append('<tr style="cursor: pointer;" onclick="getValAndClose(this);"><td>'+i+'</td><td>'+item[0].id+'</td><td>'+item[1]+'</td></tr>');
						}
					});
					
					$('#'+tbl+' tbody tr:nth-child(even)').addClass("stripped");

					if(isInitPagination){
						xIsFirstLoad = true;

						var totalRows = data.pagingInfo.totalRows;

						if(totalRows==0) {
							$('#'+tbl+' tbody').append('<tr><td colspan="25" align="center">No record found..</td></tr>');
						}

						$("#"+div+" .pagination").pagination(totalRows, 
   			                {callback:pageSelectCallbackAjaxLookup, 
   			        		items_per_page:xPageSize,
   			        		current_page:0,
   			        		num_edge_entries:2});
					}
            });
}

function getValAndClose(obj) {
	if(lookupMode == 'employee') {
		var id = $(obj).find("td:eq(1)").text();
	    var name = $(obj).find("td:eq(2)").text();
	    var phone = $(obj).find(":input[name='phone']").val();
	    var email = $(obj).find(":input[name='email']").val();
	    var address = $(obj).find(":input[name='address']").val();
	    var dept = $(obj).find(":input[name='dept']").val();
	    
	    if($(trigger).length) {
	    	$(trigger).prev().prev().val(id);
		    $(trigger).prev().val(name);
	    } else {
	    	if(inputBox == '') {
		    	inputBox = 'employee';
		    }
	    	$("input[name='"+inputBox+"']").val(id)
				.next().val(name);
	    	//FIXME : buat dinamis
	    	if(inputBox == 'gemsVerificationFindings[0].pic') {
	    		inputBox = 'gemsVerificationFindings[0].pic';
	    		$("input[name='"+inputBox+"']").val(name);
	    	}
	    	
	    	if (fieldNameInputBox=="name")
	    		$("input[name='"+singleInputBox+"']").val(name);
	    	if (phone != 'null'){
	    		$("input[name='"+customInputBox+"']").val(phone);
	    		$("input[name='"+customInputBox1+"']").val(phone);
	    	}else if (phone == 'null'){
	    		$("input[name='"+customInputBox+"']").val("");
	    		$("input[name='"+customInputBox1+"']").val("");
	    	}
	    	
	    	$("input[name='ucc.phone']").val(phone);
	    	$("input[name='ucc.email']").val(email);
	    	$("textarea[name='ucc.address']").val(address);
	    	$("input[name='empDept.tableCode']").val(dept);
	    	
	    	$("input[name='phone']").val(phone);
	    	$("input[name='email']").val(email);
	    	$("textarea[name='address']").val(address);
	    	
	    	if (mode == 'searchDepartment') {
	    		searchDepartment();
		    }
	    }
	}
	if(lookupMode == 'branch') {
		var kodeCabang = $(obj).find("td:eq(1)").text();
	    var namaCabang = $(obj).find("td:eq(2)").text();
	    var regionalBisnisName = $(obj).find(":input[name='regionalBisnisName']").val();
	    var kota = $(obj).find(":input[name='kota']").val();
	    var jumlahPenghuni = $(obj).find(":input[name='jumlahPenghuni']").val();
	    var alamat = $(obj).find(":input[name='alamat']").val();
	    
    	if(inputBox == '') {
	    	inputBox = 'branch';
	    }
    	$("input[name='"+inputBox+"']").val(kodeCabang).next().val(namaCabang).trigger('change'); //trigger change for eap
    	$("input[name='branch.regionalBisnisName']").val(regionalBisnisName);
    	$("input[name='branch.kota']").val(kota);
    	$("input[name='totalOccupant']").val(jumlahPenghuni);
    	$(":input[name='branch.alamat']").val(alamat);
    	
    	$("textarea[name='location.alamat']").val(alamat);
	}
	if(lookupMode == 'department') {
		var tableCode = $(obj).find("td:eq(1)").text();
	    var description = $(obj).find("td:eq(2)").text();
	    var tableType = $(obj).find(":input[name='tableType']").val();
	    
    	if(inputBox == '') {
	    	inputBox = 'department';
	    }
    	$("input[name='"+inputBox+"']").val(tableCode).next().val(description);
    	$("input[name='branchDept.tableType']").val(tableType);
    	$("input[name='empDept.tableType']").val(tableType);
	}
	if(lookupMode == 'selectedParties') {
		var table = $(obj).prev();
		
		var emails = [];
		table.find("input[type=checkbox]:checked").each(function(){
			if( $(this).val() != "null"){
				emails.push($(this).val());
			}
		});
    	if(inputBox == '') {
	    	inputBox = 'selectedParties';
	    }
    	if ($("input[name='"+inputBox+"']").val() != '') {
    		$("input[name='"+inputBox+"']").val($("input[name='"+inputBox+"']").val()+','+emails.join(','));
    	} else {
    		$("input[name='"+inputBox+"']").val(emails.join(','));
    	}
	}
	if(lookupMode == 'picIncident') {
		var id = $(obj).find("td:eq(1)").text();
	    var name = $(obj).find("td:eq(2)").text();
	    
    	if(inputBox == '') {
	    	inputBox = 'picIncident';
	    }
    	$("input[name='"+inputBox+"']").val(id).next().val(name);
	}
	
	lookupMode = '';
	inputBox = '';
	trigger = '';
    
    $('#'+div).hide();
    
    $('#mask, .window').hide();
}

/* 
fullName : field1[xx].field2[yy].field3
segmentName: field1, field2, field3
index : field1=xx, field2=yy
*/
function extractInputIndexSegment(fullName, segmentName) {
	var leftSegment = fullName.substr(fullName.indexOf(segmentName) + segmentName.length),
		index = leftSegment.substr(1, leftSegment.indexOf(']')-1);
	
	return ~~index;
};
 
function validateQuestInput($scope, searchQuery) {
	var valid = true;
	
	$scope.find(searchQuery).each(function(){
		if ('' == $(this).val()) {
			valid = false; 
			return false;
		}
	});

	return valid;
}

function initFakeDatebox (name, $scope){
	$scope.find(".fakedatebox").html("<input type='text' class='easyui-datebox' name='"+name+"'/>");
 	$scope.find(".easyui-datebox").datebox();
 	$scope.find(".combo-arrow").css("display", "inline-block");
};